import React from 'react';
import { Link } from 'react-router-dom'
import AddressList from 'shared/components/AddressList';
import './index.less';

const addButton = require('src/static/addbutton.png')

export default class ReceiverAddress extends React.PureComponent {
  state = {
    addressInfo: {}
  }

  renderNewAddress() {
    return (
      <div className="receiver-address-new">

        <Link to='/addressForm'>
          <img src={addButton} alt='' />
          <div>新增收货地址</div>
        </Link>
      </div>
    )
  }

  renderAddress() {
    let { defaultAddressIndex } = this.props;
    const { addresslist } = this.props;
    const { fullname, mobile, addressString } = this.state.addressInfo

    if (defaultAddressIndex === -1) {
      defaultAddressIndex = 0;
    }

    const { fullname: defaultFullname, mobile: defaultMobile,
      province, city, county, address
    } = addresslist[defaultAddressIndex]

    const defaultAddressString = `${province}${city}${county}${address}`;

    let selectedAddress;
    if (mobile) {
      selectedAddress ={ fullname, mobile, addressString }
    } else {
      selectedAddress = {
        fullname: defaultFullname,
        mobile: defaultMobile,
        addressString: defaultAddressString
      }
    }

    return (
      <div className="receiver-address-show">
        <div className="address-info">
          <span>{selectedAddress.fullname} {selectedAddress.mobile.replace(/(\d{3})(\d{4})(\d{4})/, '$1****$3')}</span>
          <span>{selectedAddress.addressString}</span>
        </div>
        <span onClick={() => { this.setState({ addressListShow: true }) }}>&gt;</span>
      </div>
    )
  }

  selectAddress = (data) => {
    this.setState(({ addressInfo: data }))

    this.props.setAddress(data);
    this.handleAddressHide()
  }

  handleAddressHide = () => {
    this.setState({ addressListShow:false })
  }

  render() {
    const { addresslist = [] } = this.props;
    return (
      <div className="receiver-address">
        {
          addresslist.length ? this.renderAddress() : this.renderNewAddress()
        }
        <AddressList
          addressHide={this.handleAddressHide}
          show={this.state.addressListShow}
          onSelectAddress={this.selectAddress}
          addresslist={addresslist}
        />
      </div>
    )
  }
}